package com.zzf.concurrent.example.sync.bean;

import com.zzf.concurrent.example.util.TimeUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author GaoFeng2017
 * @date 2019/8/6 8:40
 */
@Slf4j
public class TicketRunnable2 {

    private final static int MAX = 50;
    private int currentIndex = 1;

    /** monitor */
    private final Object LOCK = new Object();

    public void test() {

        Thread t1 = new Thread() {
            @Override
            public void run() {
                while(currentIndex <= MAX) {
                    t1();
                }
            }
        };

        Thread t2 = new Thread() {
            @Override
            public void run() {
                while(currentIndex <= MAX) {
                    t2();
                }
            }
        };

        t1.start();
        t2.start();
    }

    private synchronized void t1() {
        log.info("{} -> {}", Thread.currentThread().getName(), currentIndex++);
        TimeUtil.sleep(100000);
    }

    private void t2() {
        synchronized (LOCK) {
            TimeUtil.sleep(100);
            log.info("{} -> {}", Thread.currentThread().getName(), currentIndex++);
        }
    }
}
